/*
 * fread.c
 * Asif Shahidullah
 *
 * Handle the file reading operations as well as the creation
 * of the initial data point list.
 */

#include <stdio.h>
#include <stdlib.h>

#include "d_list.h"
#include "list_data.h"
#include "fread.h"

/* Internal function for opening the file with the necessary
 * flags.
 * Returns the file pointer on success. */
static __inline__ FILE * open_file (char *);

int create_list(List list, char *file) {
	/* Code stolen from Roman L., because I
 	 * couldn't think of a more elegant way to
 	 * do it... */  

	/* variables used for sscanf and list insertion */
	char buff[128];
	int hour_s, minute_s;
	float temperature_s;
	FILE *f_handle;
	LData data;

	/* Handle file open/close operations in this function. */
	if ((f_handle = open_file (file)) == NULL) {
		fprintf (stderr, "Failed to open input file.\n");
		return 0;
	}

	/* Checking for malloc may seem uncessary (since failure for this
	 * on a large system is rare, however due to the large volume of
	 * data which this program can potentially handle - this segment
	 * makes the program quite resiliant to malloc failures. Instead,
	 * it just skips over that data point in lieu of segfaulting. */
	while (fgets (buff, 128, f_handle)) {
		if (sscanf (buff, "%d:%d %f", &hour_s, &minute_s, &temperature_s) == 3) {
			if ((data = create_LData (hour_s, minute_s, temperature_s)) == NULL) {
				printf ("Failed to allocate space for LData object.");
			} else
				insert_node (list, list->size, data);
		}
	}

	fclose (f_handle);
	return 1;
}


FILE * open_file (char *file) {
	return fopen (file, "r");
}
